package com.yootk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 定义Locale转换器
 */
@Configuration
public class DefaultLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {   // 配置转换器
        String loc = request.getParameter("loc");
        if (!StringUtils.hasLength(loc)) {
            return Locale.getDefault();     // 使用默认的Locale实例
        } else {
            String[] split = loc.split("_");
            return new Locale(split[0], split[1]);  // 手工实例化Locale对象
        }
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }

    @Bean
    public LocaleResolver localeResolver() {    // 定义转换处理的Bean
        return new DefaultLocaleResolver();     // 返回LocaleResolver实例
    }
}
